package cn.wubo.jooq.demo.codegen;

import cn.wubo.jooq.demo.codegen.tables.records.DemotableRecord;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import static cn.wubo.jooq.demo.codegen.tables.Demotable.DEMOTABLE;

public class querydemo {

    public static void main(String[] args) {
        String jdbcUrl = "jdbc:h2:file:./data/demo;AUTO_SERVER=TRUE";
        String jdbcUsername = "sa";
        String jdbcPassword = "";

        // 获取 JDBC 链接
        try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword)) {
            // 获取 jOOQ 执行器
            DSLContext dslContext = DSL.using(connection, SQLDialect.H2);

            // fetch方法可以返回一个结果集对象 Result
            // jOOQ的Result对象实现了List接口，可以直接当做集合使用
            Result<Record> recordResult = dslContext.select().from(DEMOTABLE).fetch();
            recordResult.forEach(record -> {
                Integer id = record.getValue(DEMOTABLE.ID);
                String code = record.getValue(DEMOTABLE.CODE);
                String name = record.getValue(DEMOTABLE.NAME);
                System.out.printf("fetch Record id: %s ,code: %s ,name : %s%n", id, code, name);
            });

            // 通过 Record.into 方法可以将默认Record对象，转换为表的Record对象，例如DemotableRecord
            // Result 接口也定义了into方法，可以将整个结果集转换为指定表Record的结果集
            // 通过 DemotableRecord 可以通过get方法直接获得表对象
            // 所有表的XXXRecord对象都是实现了 Record 对象的子类
            Result<DemotableRecord> userRecordResult = recordResult.into(DEMOTABLE);
            userRecordResult.forEach(record -> {
                Integer id = record.getId();
                String code = record.getCode();
                String name = record.getName();
                System.out.printf("into Record id: %s ,code: %s ,name : %s%n", id, code, name);
            });

            // fetchInto方法可以可以传入任意class类型，或者表常量
            // 会直接返回任意class类型的List集合，或者指定表Record的结果集对象
            List<DemotableRecord> fetchIntoClassResultList = dslContext.select().from(DEMOTABLE).fetchInto(DemotableRecord.class);
            Result<DemotableRecord> fetchIntoTableResultList = dslContext.select().from(DEMOTABLE).fetchInto(DEMOTABLE);

            System.out.println("fetchIntoClassResultList: \n" + fetchIntoClassResultList);
            System.out.println("fetchIntoTableResultList: \n" + fetchIntoTableResultList);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
